package com.woniuxy.interceptor;

import com.alibaba.fastjson2.JSON;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * controller之前
     * 1.获取jwt
     * 2.解密
     * 3.拿前端的jwt和redis中的jwt做对比
     * 4.给jwt续期
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //1.获取前端请求头中的jwt
        String headerJWT = request.getHeader("authorization");
        if (headerJWT == null) {
            //响应未登录标识
            response.getWriter().print(JSON.toJSONString(new ResponseData<>().Fail(ResponseEnum.NO_LOGIN)));
            return false;
        }
        //2.用系统密钥解密
        if (!JWTUtil.decode(headerJWT)) {
            response.getWriter().print(JSON.toJSONString(new ResponseData<>().Fail(ResponseEnum.NO_LOGIN)));
            return false;
        }
        //3.拿前端jwt与redis中的jwt做对比
        Map userMap = JWTUtil.getUserMap(headerJWT);
        Long userId = (Long) userMap.get("id");
        String redisJWT = stringRedisTemplate.opsForValue().get("JWT:" + userId);
        if (!headerJWT.equals(redisJWT)) {
            response.getWriter().print(JSON.toJSONString(new ResponseData<>().Fail(ResponseEnum.NO_LOGIN)));
            return false;
        }
        //4.对jwt进行续期
        stringRedisTemplate.expire("JWT:" + userId, 15, TimeUnit.DAYS);
        return true;
    }
}
